package com.ruoyi.common.weixin;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.model.WxLoginBody;
import com.ruoyi.common.core.domain.model.WxPhoneInfo;
import com.ruoyi.common.core.domain.model.weixinPhoneInfo;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;

@Component
public class weixinHttpUtils {


    //获取用户信息
    public Object GetWeixinopenInfo(WxLoginBody wxLoginBody) {

        //http请求：
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxLoginBody.getAppId() + "&secret="
                + wxLoginBody.getAppSecret() + "&js_code=" + wxLoginBody.getCode() + "&grant_type=authorization_code";

        String respone = HttpUtils.sendGet(url);
        //解析数据
        JSONObject jsonObject = JSONObject.parseObject(respone);
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        return jsonObject;
    }


    public WxPhoneInfo getPhoneInfo(WxLoginBody wxLoginBody) throws JsonProcessingException {
        // 获取token
        // 小程序唯一标识 (在微信小程序管理后台获取)
        String appid = wxLoginBody.getAppId();
        // 小程序的 app secret (在微信小程序管理后台获取)
        String secret = wxLoginBody.getAppSecret();
        // 授权（必填）
        String grant_type = "client_credential";
        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        String params2 = "appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type;
        // 发送请求
//        String sr2 = HttpRequest.sendGet(, params2);
        String sr2 = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token?" + params2);
        // 解析相应内容（转换成json对象）
        JSONObject json2 = JSONObject.parseObject(sr2);
        String access_token = json2.getString("access_token");
        //使用获取到的token和接受到的code像微信获取手机号
        String code = wxLoginBody.getCode();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        String url = ("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token + "&code=");

//        String sr3 = HttpUtils.sendGet(url);
        String sr3 = HttpUtils.sendPost(url, JSONObject.toJSONString(jsonObject), "application/json");
//        JSONObject phone_info = JSONObject.parseObject(sr3);
        ObjectMapper mapper = new ObjectMapper();
        weixinPhoneInfo phoneinfo = mapper.readValue(sr3, weixinPhoneInfo.class);
        if (phoneinfo.getErrcode() != 0) {
            return null;
        }
        if (phoneinfo.getPhone_info() == null) {
            return null;
        }

        return phoneinfo.getPhone_info();
    }


    /**
     * AES解密
     */
    private String decrypt(String sessionKey, String encryptedIv, String encryptedData) throws Exception {
        // 转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 如果密钥不足16位，那么就补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }
        // 如果初始向量不足16位，也补足
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            //            logger.info("解析错误");
            e.printStackTrace();
        }

        // 解析加密后的字符串
        return resultStr;
    }
}
